<template>
    
    <view class="content">
        <cu-custom bgColor="bg-gradual-green" :isBack="true" zIndex="6">
            <block slot="backText"></block>
            <block slot="content" v-show="info.type==1">领养</block>
            <block slot="content" v-show="info.type==2">救助</block>
            <block slot="content" v-show="info.type==3">丢失</block>
            <block slot="content" v-show="info.type==4">帮助</block>
        </cu-custom>
        <view  @click="onShowModal" style="height:10rpx;"></view>
        <view class="cu-card dynamic ">
            <view class="cu-item shadow">
                <view class="cu-list menu-avatar">
                    <view class="cu-item">
                        <view class="cu-avatar round lg" :style="{'background-image':'url('+ info.poster.avatar +')'}"
                            @click="toNav('/pages/info/index?user_id=' + info.user_id )"></view>
                        <view class="content flex-sub">
                            <view>{{ info.poster.nickname }}</view>
                            <view class="text-gray text-sm flex justify-between">
                                {{ info.createtime_text }}
                            </view>
                        </view>
                        <view class="action text-green text-bold" style="position: relative;z-index: 999;" @click="onFocus">
                            {{ info.poster.is_focus ? '取消' : '关注'}}
                        </view>
                    </view>
                </view>
                <!-- <view class="text-content text-left">
					{{ info.content }}
				</view> -->
                <text class="text-content text-left" style="display: block;">{{ info.content }}</text>
                <view class="grid flex-sub padding-lr col-1 grid-square">
                    <view class="bg-img" :style="{'background-image':'url(' + item + ')'}" v-for="(item,index) in info.imageArray"
                        :key="index">
                    </view>
                </view>

                <view class="padding flex justify-between">
                    <view @click="onOpenLocation">
                        <text class='cuIcon-locationfill text-orange'></text>
                        <text class='text-orange'>{{ info.address }}</text>
                    </view>
                    <button class="cu-btn bg-red shadow light" @click="onShowShare">分享</button>
                </view>

                <view class="text-gray text-sm padding flex justify-between align-center">
                    <view class="flex align-center" v-if="info.type == 1">
                        <view class="cu-avatar-group" style="position: relative;">
                            <view class="cu-avatar round sm" v-for="(item,index) in info.pickupList" :key="index"
                                :style="[{ backgroundImage:'url(' + item.userinfo.avatar + ')' }]" v-if="index<5"></view>
                        </view>
                        <view class="text-black text-sm">
                            {{ info.pickupList.length }}人想领养
                        </view>
                    </view>
                    <!-- <view class="flex align-center" v-if="info.type == 2">
						<view class="text-black text-sm">
							救助金￥<text class="text-yellow">{{ info.money }}</text>
						</view>
					</view> -->
                    <view class="flex">
                        <text class="cuIcon-attentionfill margin-lr-xs"></text> {{ info.view }}
                        <text class="cuIcon-appreciatefill margin-lr-xs"></text> {{ info.like.number }}
                        <text class="cuIcon-messagefill margin-lr-xs"></text> {{ info.replies }}
                    </view>

                </view>



                <view class="cu-list menu-avatar comment padding">
                    <button class="cu-btn bg-blue shadow light fl" v-if="info.type == 1" @click="onPickup">申请领养</button>
                    <button class="cu-btn bg-red shadow light fl" v-if="info.type == 2" style="margin-right: 20rpx;"
                        @click="toNav('/pages/goods/rescue?url='+info.donate_image)">捐赠爱心</button>
                    <!-- <button class="cu-btn bg-blue shadow light fl" v-if="info.type == 2" @click="toNav('/pages/mine/helps?post_id='+info.post_id)">捐赠名单</button> -->
                    <button class="cu-btn bg-orange shadow light fr" @click="onReply()">回复楼主</button>
                </view>

                <!--<view class="cu-list menu-avatar comment padding">
					<button class="cu-btn bg-blue shadow light ">提供线索</button>
				</view>
				<view class="cu-list menu-avatar comment padding">
					<button class="cu-btn bg-blue shadow light ">点击帮助</button>
				</view> -->
                <!-- 广告 -->
                <ad unit-id="adunit-2ada3ddab89569ad"></ad>
                <!-- 回复 -->
                <view class="cu-list menu-avatar comment solids-top">
                    <view class="cu-item" v-for="(item,index) in info.replyList" :key="index">
                        <view class="cu-avatar round" :style="{'background-image':'url(' + item.user.avatar + ')'}"></view>
                        <view class="content">
                            <view class="text-grey">{{ item.user.nickname }}</view>
                            <view class="text-gray text-content text-df">
                                {{ item.content }}
                            </view>

                            <view class="bg-grey padding-sm radius margin-top-sm  text-sm" v-if="item.subReply" v-for="( e,i ) in item.subReply"
                                :key="i">
                                <view class="flex ">
                                    <view class="flex light" style="flex-direction: column;flex:11;">
                                        <view><text class="text-olive ">{{ e.user.nickname }}</text>&nbsp;&nbsp;回复&nbsp;&nbsp;<text
                                                class="text-olive">{{ e.replyUser.nickname}}</text>:</view>
                                        <view class="flex-sub">{{e.content}}</view>
                                    </view>

                                    <text class="cuIcon-messagefill text-white margin-left-sm flex-sub" @click="onReplyIn(item,e,index)"></text>
                                </view>
                            </view>

                            <view class="margin-top-sm flex justify-between">
                                <view class="text-gray text-df">{{ item.createtime_text }}</view>
                                <view>
                                    <text class="cuIcon-messagefill text-gray margin-left-sm" @click="onReplyLay(item,index)"></text>
                                </view>
                            </view>
                        </view>
                    </view>

                </view>
            </view>
        </view>

        <view class="cu-tabbar-height"></view>

        <view class="cu-bar foot input" style="z-index: 1;" :style="[{bottom:InputBottom+'px'}]">
            <view class="action">
                <button class="cu-btn bg-red shadow" @click="onlike">{{ info.like.is_like ? '取消' : '点赞' }}</button>
            </view>
            <input class="solid-bottom" :adjust-position="false" :focus="false" maxlength="300" cursor-spacing="10"
                @focus="InputFocus" @blur="InputBlur" v-model="inputVal" :placeholder="placeholder"></input>
            <!-- <view class="action">
				<text class="cuIcon-emojifill text-grey"></text>
			</view> -->
            <button class="cu-btn bg-green shadow" @click="submitReply">发送</button>
        </view>

        <!-- 加载 -->
        <view class="cu-load load-modal" v-if="loadModal">
            <!-- <view class="cuIcon-emojifill text-orange"></view> -->
            <image src="/static/logo.png" mode="aspectFit"></image>
            <view class="gray-text">加载中...</view>
        </view>
        <!-- 捐赠 -->
        <view class="cu-modal bottom-modal" :class=" showModal ? 'show' : '' ">
            <view class="cu-dialog">
                <view class="cu-bar bg-white">
                    <view class="action text-blue" @click="hideModal">取消</view>
                    <view class="action text-green" @click="onSubmit">确定</view>
                </view>
                <view class="padding">
                    <view class="padding">
                        <input type="digit" v-model="monyVal" style="height:80rpx;line-height: 80rpx;" placeholder="您想捐赠的金额"
                            class="bg-white">
                    </view>
                </view>
            </view>
        </view>

        <!-- 底部弹窗 -->
        <view class="cu-modal bottom-modal" :class="showShare?'show':''" @click="hideShowShare">
            <view class="cu-dialog" @click.stop="">
                <view class="padding-xl">
                    <view class="grid col-2 text-center">
                        <view style="position:relative;">
                            <image src="../../static/share-icon2.png" mode="widthFix" style="width: 120rpx;"></image>
                            <button open-type="share" style="opacity: 0;position: absolute;left:0;right:0;top:0;bottom:0;"></button>
                            <view>微信好友</view>
                        </view>
                        <view @click="onJumpCode">
                            <image src="../../static/share-icon1.png" mode="widthFix" style="width: 120rpx"></image>
                            <view>分享朋友圈</view>
                        </view>
                    </view>
                </view>
            </view>
        </view>
        <!-- 分享二维码 -->
        <!-- <view class="cu-modal bottom-modal" :class="showCode?'show':''" @click="hideShowCode">
            <view class="code" v-if="showCode">
                <wm-poster @success="onSuccess" :imgSrc="info.imageArray[0]" :QrSrc="'https://wzlive.club/qrcode/build?text=https://wzlive.club/jump?post_id='+post_id"
                     :Referrer="info.poster.nickname+'推荐给您'" :PriceTxt="info.content" PriceColor="#39b54a" success="onSuccess"></wm-poster>
            </view>
            <button class="cu-btn bg-blue shadow light lg" v-if="url" open-type="openSetting" @opensetting='handleSetting' style="position: absolute;bottom:30rpx;left:50%;transform: translate(-50%,0);">保存</button>
            <button class="cu-btn bg-blue shadow light lg" v-if="url && openSettingBtnHidden" @click="saveEwm" style="position: absolute;bottom:30rpx;left:50%;transform: translate(-50%,0);">保存</button>
        </view> -->
        <hchPoster ref="hchPoster" :canvasFlag.sync="canvasFlag" @cancel="canvasCancel" :posterObj.sync="posterData" />
        <view :hidden="canvasFlag">
            <!-- 海报 要放外面放组件里面 会找不到 canvas-->
            <canvas class="canvas" canvas-id="myCanvas"></canvas><!-- 海报 -->
        </view>
    </view>
</template>

<script>
    import hchPoster from '../../wxcomponents/hch-poster/hch-poster.vue'
    import wmPoster from "@/components/wm-poster/wm-poster.vue";
    import {
        mapState,
        mapActions
    } from 'vuex';
    export default {
        components: {
            hchPoster,
            wmPoster
        },
        data() {
            return {
                InputBottom: 0,
                post_id: '',
                info: '',
                loadModal: false,
                inputVal: '', //回复内容
                placeholder: '回复:楼主',
                parent_reply_id: '', //	最上级回复id
                reply_user_id: '', //@的人id 回复对象
                reply_user_number: '',
                showModal: false,
                monyVal: '',
                showShare: false,
                showCode: false,
                url: '',
                openSettingBtnHidden: true, //是否授权
                deliveryFlag: false,
                canvasFlag: true,
                posterData: {},
                anm:1
            }
        },
        // onPullDownRefresh() {
        // 	this.getPost();
        // },
        onLoad(option) {
            // this.post_id = option.post_id;
            // console.log(option)
            if (option.post_id) {
                console.log(11)
                this.post_id = option.post_id;

            } else {
                console.log(22)
                console.log(option.q)
                let str = decodeURIComponent(decodeURIComponent(option.q));
                console.log(str)

                function getParam(name) {
                    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
                    var r = str.split("?")[1].match(reg); //匹配目标参数
                    if (r != null) {
                        return decodeURIComponent(r[2]);

                    }
                    return null; //返回参数值
                }
                this.post_id = getParam('post_id');
                console.log(this.post_id, 123123)
            }
            this.getPost();
        },
        onShareAppMessage(res) {
            if (res.from === 'button') { // 来自页面内分享按钮
                console.log(res.target)
            }
            return {
                title: this.info.content,
                path: '/pages/goods/adopt?post_id=' + this.info.post_id,
                imageUrl: this.info.imageArray[0],
            }
        },
        created() {
            // this.getPost();
        },
        onShow() {
            // this.getPost();
        },
        methods: {
            onJumpCode() {
                console.log(this.info)
                uni.setStorage({
                    key: 'codeInfo',
                    data: this.info,
                    success() {
                        uni.navigateTo({
                            url: '/pages/goods/code'
                        })
                    }
                })

            },
            createCanvasImageEvn() {
                this.showShare = false;
                // 这个是固定写死的小程序码
                Object.assign(this.posterData, {
                    url: this.info.imageArray[0], //商品主图
                    icon: '', //醉品价图标
                    title: this.info.content, //标题
                    discountPrice: "", //折后价格
                    orignPrice: "", //原价
                    code: 'https://wzlive.club/qrcode/build?text=https://wzlive.club/jump?post_id=' + this.post_id, //小程序码
                })
                this.$forceUpdate(); //强制渲染数据
                setTimeout(() => {
                    this.canvasFlag = false; //显示canvas海报
                    this.deliveryFlag = false; //关闭分享弹窗
                    this.$refs.hchPoster.createCanvasImage(); //调用子组件的方法
                }, 500)
            },
            // 分享弹窗
            shareEvn() {
                this.deliveryFlag = true;
            },
            // 关闭分享弹窗
            closeShareEvn() {
                this.deliveryFlag = false;
            },
            // 取消海报
            canvasCancel(val) {
                this.canvasFlag = val;
            },
            handleSetting(e) {
                if (!e.detail.authSetting['scope.writePhotosAlbum']) {
                    this.openSettingBtnHidden = false;
                } else {
                    this.openSettingBtnHidden = true;
                }
            },
            saveEwm: function(e) {
                let _self = this;
                //获取相册授权
                uni.getSetting({
                    success(res) {
                        if (!res.authSetting['scope.writePhotosAlbum']) {
                            uni.authorize({
                                scope: 'scope.writePhotosAlbum',
                                success() {
                                    //这里是用户同意授权后的回调
                                    _self.saveImgToLocal();
                                },
                                fail() { //这里是用户拒绝授权后的回调
                                    _self.openSettingBtnHidden = false
                                }
                            })
                        } else { //用户已经授权过了
                            _self.saveImgToLocal();
                        }
                    }
                })
            },
            saveImgToLocal: function(e) {
                let _self = this;
                uni.showModal({
                    title: '提示',
                    content: '确定保存到相册吗',
                    success: function(res) {
                        if (res.confirm) {

                            uni.downloadFile({
                                url: _self.url, //图片地址
                                success: (res) => {
                                    console.log(res)
                                    if (res.statusCode === 200) {
                                        uni.saveImageToPhotosAlbum({
                                            filePath: res.tempFilePath,
                                            success: function() {
                                                uni.showToast({
                                                    title: "保存成功",
                                                });
                                            },
                                            fail: function() {
                                                uni.showToast({
                                                    title: "保存失败",
                                                    icon: "none"
                                                });
                                            }
                                        });
                                    }
                                },
                                fail: (err) => {
                                    console.log(err)
                                }

                            })


                        } else if (res.cancel) {

                        }
                    }
                });
            },
            onSuccess(e) {
                this.url = e.tempFilePath;
                uni.hideLoading();
                console.log(e, 1111)
            },
            hideShowCode() {
                this.showCode = false;
            },
            onShowCode() {
                uni.showLoading({
                    title: '生成中...'
                })
                this.showCode = true;
            },
            hideShowShare() {
                this.showShare = false;
            },
            onShowShare() {
                this.showShare = true;
            },
            onPickup() {

                if (!this.$store.state.userinfo.mobile) {
                    uni.showToast({
                        title: '请先完善完个人资料',
                        icon: 'none'
                    })

                    setTimeout(() => {
                        uni.navigateTo({
                            url: '/pages/mine/setData'
                        })
                    }, 1000)

                    return;
                }

                this.$http.post('pickup', {
                    post_id: this.post_id
                }).then(res => {
                    if (res.code == 1) {
                        uni.showToast({
                            title: '申请领养成功',
                        })
                    }
                    console.log(res)
                })
            },
            onShare() {
                console.log(111)
                uni.showShareMenu({
                    withShareTicket: true,
                    title: '快来帮助一下可怜的宠物',
                    path: '/pages/goods/adopt?post_id=' + this.info.post_id,
                    imageUrl: this.info.images,
                    desc: this.info.content
                }).then(res => {
                    console.log(res)
                })
            },
            InputFocus(e) {
                this.InputBottom = e.detail.height
            },
            InputBlur(e) {
                this.InputBottom = 0
            },
            toNav(link) {
                uni.navigateTo({
                    url: link
                })
            },
            //获取接口
            getPost() {
                this.loadModal = true;
                this.$http.post('getPost', {
                    post_id: this.post_id
                }).then(res => {
                    this.info = res.data;
                    this.loadModal = false;
                }).catch(err => {
                    this.loadModal = false;
                })

            },
            onShowModal() {
                this.anm++;
                if(this.anm==5){
                    this.showModal = true;
                    this.anm = 1;
                }
            },
            hideModal() {
                this.showModal = false;
            },
            onSubmit() {
                if (!this.monyVal) {
                    uni.showToast({
                        title: '金额不能为空',
                        icon: 'none'
                    })
                    return;
                }
                this.$http.post('jdonate', {
                    post_id: this.post_id,
                    price: this.monyVal * 1
                }).then(res => {
                    console.log(res)

                    if (res.code == 1) {
                        let data = res.data;
                        this.$http.post('pay', {
                            order_no: data.order_no,
                            pay_type: 'wechat',
                            openId: this.$store.state.userinfo.openid,
                            pay_method: 'miniapp'
                        }).then(re => {
                            let pdata = JSON.parse(re.data);
                            console.log(JSON.parse(re.data))
                            uni.requestPayment({
                                provider: 'wxpay',
                                timeStamp: pdata.timeStamp,
                                nonceStr: pdata.nonceStr,
                                package: pdata.package,
                                signType: pdata.signType,
                                paySign: pdata.paySign,
                                success: function(res) {
                                    console.log('success:' + JSON.stringify(res));
                                },
                                fail: function(err) {
                                    console.log('fail:' + JSON.stringify(err));
                                }
                            });
                        })
                    }
                })


                this.showModal = false;


            },
            onReply(isBoo = false) {
                if (!isBoo) {
                    this.placeholder = '回复:楼主';
                }

                this.parent_reply_id = '';
                this.reply_user_id = '';
                this.reply_user_number = '';
            },
            onReplyLay(item, index) {
                console.log(index)
                this.onReply(true)

                this.placeholder = '回复:' + item.user.nickname;
                this.parent_reply_id = item.id;
                this.reply_user_id = item.user_id;
                this.reply_user_number = index + '';
                console.log(this.reply_user_number)
            },
            onReplyIn(item, e, index) {
                this.onReply(true)

                this.placeholder = '回复:' + e.user.nickname;
                this.parent_reply_id = item.id;
                this.reply_user_id = e.user_id;
                this.reply_user_number = index + '';
            },
            submitReply() {

                if (!this.inputVal) {
                    uni.showToast({
                        title: '回复为空',
                        icon: 'none'
                    })
                    return;
                }

                let form = {
                    post_id: this.post_id,
                    content: this.inputVal,
                    parent_reply_id: this.parent_reply_id,
                    reply_user_id: this.reply_user_id
                }

                this.$http.post('submitReply', form).then(res => {

                    console.log(res);
                    let data = res.data;

                    if (this.reply_user_number === '') {
                        this.info.replyList.unshift(data);
                    } else {
                        this.info.replyList[this.reply_user_number].subReply.push(data);
                    }

                    this.inputVal = '';
                    this.onReply(); //清空

                    uni.showToast({
                        title: '回复成功'
                    })
                })
            },
            onlike() {
                let form = {
                    type: 2,
                    target_id: this.post_id
                }

                this.$http.post('focus', form).then(res => {
                    if (res.data.status) {
                        this.info.like.number++;
                        uni.showToast({
                            title: '点赞成功'
                        })
                    } else {
                        this.info.like.number--;
                        uni.showToast({
                            title: '取消点赞'
                        })
                    }
                    this.info.like.is_like = res.data.status;
                })
            },
            onFocus() {
                console.log(11)
                let form = {
                    type: 1,
                    target_id: this.info.user_id
                }

                this.$http.post('focus', form).then(res => {
                    if (res.data.status) {

                        uni.showToast({
                            title: '关注成功'
                        })
                    } else {
                        uni.showToast({
                            title: '取消关注'
                        })
                    }
                    console.log(res)
                    this.info.poster.is_focus = res.data.status;
                })
            },
            onOpenLocation() {
                uni.openLocation({
                    latitude: this.info.lat * 1,
                    longitude: this.info.lng * 1
                }).then(res => {
                    console.log(res)
                })
            }
        }
    }
</script>

<style scoped lang="less">
    .cu-bar {
        padding-bottom: calc(env(safe-area-inset-bottom) / 2);
    }

    .canvas {
        position: fixed !important;
        top: 0 !important;
        left: 0 !important;
        display: block !important;
        width: 100% !important;
        height: 100% !important;
        z-index: 10;
    }
</style>
